#include "logger.h"
#include <time.h>
#include <iostream>

Logger &Logger::GetInstance()
{
    static Logger logger;
    return logger;
}

Logger::Logger()
{
    std::thread writeLogTask([&]()
                             {
       for(;;)
       {
        // 获取当天的日期，写入日志的相应文件
            time_t now = time(nullptr);
            tm*  t =localtime(&now);
            char file_name[128]={0};
            sprintf(file_name,"%d-%d-%d-log.txt",t->tm_year+1900,t->tm_mon+1,t->tm_mday);
           FILE* pf =  fopen(file_name,"a+");
           if(pf==nullptr)
           {
            std::cout<<"logger file:"<<file_name<<" open error"<<std::endl;
            exit(EXIT_FAILURE);
           }
           // 打开之后，写数据
           std::string message = m_queue.Pop();

           char buf[128]={0};
           sprintf(buf,"%d:%d:%d =>[%s]",t->tm_hour,t->tm_min,t->tm_sec,(m_loglevel==INFO?"INFO":"ERROR"));
           message.insert(0,buf);
           message.append("\n");
           fputs(message.c_str(),pf);
           fclose(pf);
       } });

    // 设置分离线程
    writeLogTask.detach();
}
void Logger::SetLogLevel(LogLevel level)
{
    m_loglevel = level;
}

void Logger::Log(std::string message)
{
    // 写日志
    // 把日志信息写到缓冲区种
    m_queue.Push(message);
}
